import React, { Component } from 'react';
import { subscribe, sendMsg } from '../lib/socket';
import './index.css';

class Msg extends Component {
    componentDidMount() {
        let _this = this;
        const { msg, userName, readMsg } = this.props;
        let timer;
        // 方法1 ： 

        // if ((msg.author != userName) && !msg.isRead) {
        //     timer = setInterval(function () {
        //         _this.changeMsgReadStatus();
        //     }, 1000);
        // } else {
        //     clearInterval(timer);
        // }

        // 方法2: 使用IntersectionObserver
        if ((msg.author != userName) && !msg.isRead) {
            var io = new IntersectionObserver(function () {
                _this.changeMsgReadStatus();
            }, {
                    rootMargin: "50px",
                    threshold: [0.5],
                });
            io.observe(this._dom);
        }

    }

    // 选择一个时候更新阅读状态
    changeMsgReadStatus() {
        const { msg, readMsg } = this.props;
        let marginBottom = this._dom.getBoundingClientRect().bottom;
        // console.log(marginBottom);
        if (marginBottom > 0 && marginBottom < 700) {
            readMsg(msg.id);
        }
    }
    render() {
        const { msg, userName, } = this.props;
        return (

            <div className="msg" ref={msg => this._dom = msg}>
                {
                    msg.type === 'message' ? <li className={msg.author === userName ? 'me' : 'othoer'}>
                        <div className="user">{msg.author}
                            {
                                <span className={!msg.isRead && 'unread'}>
                                    （{
                                        msg.isRead ? '已读' : '未读'
                                    }）

                                </span>
                            }
                        </div>
                        <div className="time">{msg.time}</div>
                        <div className="detail">
                            <span>{msg.content}</span></div>
                    </li> : <li className="info">
                            <span>{msg.content}</span>
                        </li>

                }
            </div>

        );
    }
}

export default Msg;
